class_name Shop
extends Control

# ===============================================

signal unit_bought(unit: UnitStats)

# ===============================================

@export var player_stats: PlayerStats
@export var unit_pool: UnitPool

# ===============================================

@onready var shop_cards: VBoxContainer = $Top/ShopCards
@onready var unit_card_scene_spawner: SceneSpawner = $UnitCardSceneSpawner

const CARDS_COUNT: int = 5

# ===============================================

func __on_unit_bought(unit:UnitStats) -> void:
	unit_bought.emit(unit)


func __roll_units() -> void:
	for i in CARDS_COUNT:
		var rarity: UnitStats.Rarity = player_stats.get_random_rarity_for_level()
		var new_card: UnitCard = unit_card_scene_spawner.spawn_scene(shop_cards) as UnitCard
		new_card.unit_stats = unit_pool.get_random_unit_by_rarity(rarity)
		new_card.unit_bought.connect(__on_unit_bought)


func __put_back_remaining_to_pool() -> void:
	for unit_card: UnitCard in shop_cards.get_children():
		if not unit_card.bought:
			unit_pool.add_unit(unit_card.unit_stats)
		unit_card.queue_free()

# ===============================================

func _ready() -> void:
	unit_pool.generate_unit_pool()
	for child: Node in shop_cards.get_children():
		child.queue_free()
	__roll_units()


func _on_reroll_button_pressed() -> void:
	__put_back_remaining_to_pool()
	__roll_units()
